package com.miniprogram.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miniprogram.api.service.ICustomerUserTokenService;
import com.miniprogram.bean.po.CustomerUser;
import com.miniprogram.api.mapper.CustomerUserMapper;
import com.miniprogram.api.service.ICustomerUserService;
import com.miniprogram.bean.po.CustomerUserToken;
import com.miniprogram.common.enums.RestStatusEnum;
import com.miniprogram.common.service.BaseServiceImpl;
import com.miniprogram.common.utils.Shift;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 顾客用户表 服务实现类
 * </p>
 *
 * @author lin
 * @since 2020-04-06
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CustomerUserServiceImpl extends BaseServiceImpl<CustomerUserMapper, CustomerUser> implements ICustomerUserService {

    @Autowired
    private ICustomerUserTokenService iCustomerUserTokenService;

    @Override
    public CustomerUser getByOpenId(String openId){
        QueryWrapper<CustomerUser> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id",openId);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public CustomerUserToken login(String account, String password) {
        CustomerUser user = this.getByAccountAndPassword(account,password);
        if (user == null) {
            Shift.fatal(RestStatusEnum.OTHER,"账号密码不正确");
        }
        if (user.getStatus() == 0) {
            Shift.fatal(RestStatusEnum.OTHER,"您的账号已被禁用");
        }
        return iCustomerUserTokenService.createTokenForLogin(user);
    }

    @Override
    public CustomerUser getByAccountAndPassword(String account, String password){
        QueryWrapper<CustomerUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CustomerUser::getAccount,account).eq(CustomerUser::getPassword,password);
        return this.getOne(wrapper);
    }
}
